package com.sxhalo.fsms.log;

import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sxhalo.fsms.domain.LogException;
import com.sxhalo.fsms.domain.LogOperation;
import com.sxhalo.fsms.domain.UserInfo;
import com.sxhalo.fsms.service.ILogExceptionService;
import com.sxhalo.fsms.service.ILogOperationService;
import com.sxhalo.fsms.service.IUserInfoService;
import com.sxhalo.fsms.util.CookieUtils;
import com.sxhalo.fsms.util.TokenUtil;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 切面处理类，操作日志异常日志记录处理
 *
 * @author
 * @date
 */
@Aspect
@Component
public class OperLogAspect {

	protected ObjectMapper oMapper = new ObjectMapper().setSerializationInclusion(Include.NON_NULL);

	@Autowired
	private ILogOperationService operationLogService;
	@Autowired
	private ILogExceptionService exceptionLogService;

	@Autowired
	private IUserInfoService userInfoService;

	/**
	 * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
	 */
	@Pointcut("@annotation(com.sxhalo.fsms.log.SysControllerLog)")
	public void operLogPoinCut() {
	}

	/**
	 * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
	 */
	@Pointcut("execution(* com.sxhalo.fsms.controller.api.*Controller.*(..))")
	public void operExceptionLogPoinCut() {
	}

	/**
	 * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
	 *
	 * @param joinPoint 切入点
	 *
	 */
	@AfterReturning(pointcut = "operLogPoinCut()")
	public void saveOperLog(JoinPoint joinPoint) {
		// 获取RequestAttributes
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		// 从获取RequestAttributes中获取HttpServletRequest的信息
		HttpServletRequest request = (HttpServletRequest) requestAttributes
				.resolveReference(RequestAttributes.REFERENCE_REQUEST);
		Integer userId = null;
		String token = CookieUtils.getCookieValue(request, "token");
		if (token != null) {
			userId = TokenUtil.getUserId(token);
		}
		UserInfo user = userInfoService.selectByPrimaryKey(userId);
		Timestamp nowTime = new Timestamp(System.currentTimeMillis());
		Map<?, ?> param = converMap(request.getParameterMap());
		try {
			Object[] oArgs = joinPoint.getArgs();
			// 从切面织入点处通过反射机制获取织入点处的方法
			MethodSignature signature = (MethodSignature) joinPoint.getSignature();
			// 获取切入点所在的方法
			Method method = signature.getMethod();
			// 获取操作
			SysControllerLog opLog = method.getAnnotation(SysControllerLog.class);
			if (opLog != null) {
				LogOperation log = new LogOperation();

				String operationName = opLog.operationName();
				String modelName = opLog.modelName();
				log.setModuleName(modelName);
				log.setOperationName(operationName);
				log.setCreateTime(nowTime);
				if (user != null) {
					log.setUserId(userId);
					log.setUserName(user.getUserName());
				}
				log.setMachineIp(getIp(request));
				if (param.size() > 0) {
					log.setOperationData(param != null ? oMapper.writeValueAsString(param) : null);
				} else {
					log.setOperationData(oArgs[0] != null ? oMapper.writeValueAsString(oArgs[0]) : null);
				}
				operationLogService.insertSelective(log);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		return ip;
	}

	/**
	 * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
	 *
	 * @param joinPoint 切入点
	 * @param e         异常信息
	 */
	@AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
	public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
		// 获取RequestAttributes
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		// 从获取RequestAttributes中获取HttpServletRequest的信息
		HttpServletRequest request = (HttpServletRequest) requestAttributes
				.resolveReference(RequestAttributes.REFERENCE_REQUEST);
		Integer userId = null;
		String token = CookieUtils.getCookieValue(request, "token");
		if (token != null) {
			userId = TokenUtil.getUserId(token);
		}
		UserInfo user = userInfoService.selectByPrimaryKey(userId);
		Timestamp nowTime = new Timestamp(System.currentTimeMillis());
		Map<?, ?> param = converMap(request.getParameterMap());
		try {
			Object[] oArgs = joinPoint.getArgs();
			// 从切面织入点处通过反射机制获取织入点处的方法
			MethodSignature signature = (MethodSignature) joinPoint.getSignature();
			// 获取切入点所在的方法
			Method method = signature.getMethod();
			// 获取操作
			SysControllerLog opLog = method.getAnnotation(SysControllerLog.class);
			if (opLog != null) {
				LogException log = new LogException();

				String operationName = opLog.operationName();
				String modelName = opLog.modelName();
				log.setModuleName(modelName);
				log.setOperationName(operationName);
				log.setCreateTime(nowTime);
				log.setMachineIp(getIp(request));
				if (user != null) {
					log.setUserId(userId);
					log.setUserName(user.getUserName());
				}
				if (param.size() > 0) {
					log.setOperationData(param != null ? oMapper.writeValueAsString(param) : null);
				} else {
					log.setOperationData(oArgs[0] != null ? oMapper.writeValueAsString(oArgs[0]) : null);
				}

				log.setMessage(stackTraceToString(e.toString(), e.getMessage(), e.getStackTrace()));
				exceptionLogService.insertSelective(log);
			}
		} catch (Exception e2) {
			e2.printStackTrace();
		}
	}

	/**
	 * 转换request 请求参数
	 *
	 * @param paramMap request获取的参数数组
	 */
	public Map<String, String> converMap(Map<String, String[]> paramMap) {
		Map<String, String> rtnMap = new HashMap<String, String>();
		for (String key : paramMap.keySet()) {
			rtnMap.put(key, paramMap.get(key)[0]);
		}
		return rtnMap;
	}

	/**
	 * 转换异常信息为字符串
	 *
	 * @param exceptionName    异常名称
	 * @param exceptionMessage 异常信息
	 * @param elements         堆栈信息
	 */
	public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
		StringBuffer strbuff = new StringBuffer();
		for (StackTraceElement stet : elements) {
			strbuff.append(stet + "\n");
		}
		String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
		return message;
	}
}